#include "FriendlyMissile.h"
#include <QtOpenGL>
#include <QPainter>

namespace QtTutorial4
{
	/**
	Constructor
	*/
	FriendlyMissile::FriendlyMissile(QGraphicsItem *parent):
			QGraphicsItem(parent),
			mExploded(false),
			mExploding(false),
			mExplodeTime(0),
			mAngle(0)
	{
	}

	/**
	Destructor
	*/
	FriendlyMissile::~FriendlyMissile()
	{
	}

	/**
	Initializes the missile
	*/
	void FriendlyMissile::initialize(QString inAppDirectory)
	{
		mApplicationDirectory = inAppDirectory;
		mExplosion.load(inAppDirectory+"spotlight.png");
		mImage.load(inAppDirectory+"missile.png");
		setSize(QSizeF(25,25));
	}

	/**
	Returns the bounding rectangle of this object
	*/
	QRectF FriendlyMissile::boundingRect() const
	{
		return QRectF(QPointF(-mSize.width(), -mSize.height()) * 0.5f, mSize);
	}

	/**
	Checks if a coordinate is inside this object
	*/
	const bool FriendlyMissile::isInside(QPointF inPos) const
	{
		return boundingRect().contains(mapFromParent(inPos));
	}

	/**
	* Updates the missile. Updates position based on direction and scale, updates trace and 
	* explosion when appropriate.
	*/
	void FriendlyMissile::update(float inFrameTime)
	{
		QVector2D direction = mTargetPosition - QVector2D(pos());
		direction.normalize();

		mAngle = Blobz::radToDeg(acosf(QVector2D::dotProduct(direction, QVector2D(1,0))));

		float part = mExplodeTime / 0.5f;
		mTrailEndPos = -(direction * ((1-part)*100.0f*scale()));
		if(!mExploding)
			setPos(pos() + (direction*(inFrameTime*300.0f*scale())).toPointF());
		
		// Sets to explode when close enough to the target.
		if(!mExploding && (QVector2D(pos()) - mTargetPosition).lengthSquared() < 5.0 * 5.0 * scale())
		{
			mExploding = true;
		}

		// Exploding effect created by increasing the size of the missile. Removal of exploding 
		// missiles is handled by the application.
		if(mExploding)
		{
			mExplodeTime+= inFrameTime;
			mSize += (mSize * inFrameTime*2.0f);
			if(mExplodeTime > 0.5f)
			{
				mExploded = true;
			}
		}
	}

	/**
	* Draws the missile. 
	*/
	void FriendlyMissile::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget /* = 0 */)
	{
		// Apply the transformation and draw from the objects basis.
		painter->save();
		painter->setTransform(transform(), true);

		painter->setPen(Qt::green);
		if(mTrailEndPos.lengthSquared() > 0.0f)
			painter->drawLine(QPointF(0,0), mTrailEndPos.toPointF()/* = -direction * length */);

		// The sprite is drawn to the set size of the missile using the boundingRect. 
		// Scaling and positioning is handled by setTransform.
		QRectF rect = boundingRect();
		if(!mExploding)
		{
			// Missile is rotated to go be angled in the direction it is traveling.
			painter->rotate(-mAngle + 90);
			painter->drawImage(rect, mImage);
		}
		else
		{
			painter->drawImage(rect, mExplosion);
		}

		painter->restore();
	}
}
